<template>
  <view class="content">
    <u-loading-page :loading="loadingPage"></u-loading-page>
    <u-navbar
      v-if="showNavbar"
      :title="originData.title"
      safeAreaInsetTop
      fixed
      placeholder
    >
      <view slot="left">
        <u-icon v-if="isBack" name="arrow-left" size="22" @click="closePage" />
      </view>
      <view slot="right">
        <u-icon
          v-if="isShare"
          @click="shareClickHandle"
          name="share-square"
          size="22"
        />
      </view>
    </u-navbar>
    <view :style="{ 'pointer-events': isPreview ? 'none' : '' }">
      <low-code-page
        ref="lpgs"
        hideNavbar
        @event="listenEvent"
        v-if="pageData && !submitSuccess && pageStatus"
        :pageJson="pageData"
      />
    </view>
    <view class="submit-success-view" v-if="submitSuccess || !pageStatus">
      <u-navbar
        v-if="showNavbar"
        :title="originData.title"
        safeAreaInsetTop
        fixed
        placeholder
      >
        <view slot="left" @click="closePage">
          <u-icon name="close" size="22" />
        </view>
        <view slot="right">
          <u-icon
            v-if="isShare"
            @click="shareClickHandle"
            name="share-square"
            size="22"
          />
        </view>
      </u-navbar>
      <view class="tips-panel">
        <view class="xy-center">
          <image
            class="img"
            :src="
              formIsDeleted || !pageStatus
                ? '/static/form-disable.png'
                : '/static/submit-success.png'
            "
            mode="scaleToFill"
          />
          <u--text
            size="18"
            bold
            :text="
              formIsDeleted || !pageStatus
                ? !pageStatus
                  ? '二维码已失效'
                  : '表单已删除，无法提供服务'
                : '提交成功'
            "
            align="center"
          />
        </view>
      </view>
      <view class="sild-bar" v-if="merchantQrCode">
        <u--text
          size="14"
          bold
          text="长按识别二维码，快来商店逛逛吧"
          align="left"
        />
        <view class="qrcode">
          <image class="qrImg" :src="merchantQrCode" mode="scaleToFill" />
        </view>
      </view>
    </view>

    <view v-if="loadDone && !pageData" class="emp-page">
      <u-empty
        mode="page"
        text="活动不存在"
        icon="http://cdn.uviewui.com/uview/empty/page.png"
      />
    </view>

    <view
      class="share-panel"
      :style="{
        'background-color': sharePanelVisible ? ' #00000031' : ' #00000000',
        top: panelTop,
      }"
    >
      <view
        class="share-content"
        :style="{ bottom: sharePanelVisible ? '0rpx' : '-395rpx' }"
      >
        <view class="hd">
          <u--text text="立即分享给好友" size="15" align="center"></u--text>
        </view>
        <view class="bd">
          <view class="item" @click="showPosters">
            <image class="img" src="/static/poster.png" mode="scaleToFill" />
            <u--text
              align="center"
              text="分享海报"
              size="13"
              color="#000"
            ></u--text>
          </view>
          <view class="item" @click="shareToWechat">
            <image class="img" src="/static/wechat.png" mode="scaleToFill" />
            <u--text
              align="center"
              text="微信"
              size="13"
              color="#000"
            ></u--text>
          </view>
        </view>
        <view class="ft" @click="sharePanelVisible = false">
          <u--text align="center" text="取消" size="14" color="#fff"></u--text>
        </view>
      </view>
    </view>
    <u-popup
      :show="postersVisible"
      mode="center"
      @close="hidePosters"
      closeOnClickOverlay
      :customStyle="{ backgroundColor: 'rgba(0,0,0,0)' }"
    >
      <view class="posters-content">
        <view class="posters-bd">
          <view class="close-icon" @click.stop="hidePosters">
            <u-icon name="close" color="#3D3D3D" size="24" />
          </view>
          <image
            class="posters-img"
            v-if="pageData"
            :src="pageData.posterBackgroundImage"
            mode="aspectFit"
          />
        </view>
        <view class="posters-btn" @click="shareToFriend"> 分享给好友 </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import { getList, isBindWxapp, sendData } from "@/service/api/system";
import { getWxAppQrcode } from "@/service/api/widget";
export default {
  data() {
    return {
      pageData: null,
      pageId: null,
      loadingPage: false,
      loadDone: false,
      submitSuccess: false,
      originData: {},
      sharePanelVisible: false,
      panelTop: "100vh",
      isBack: false,
      isShare: false,
      merchantQrCode: "",
      postersVisible: false,
      formIsDeleted: "",
      showNavbar: true,
      // isPreview: false,
      pageStatus: 1,
      noCover:
        "https://hyyxboss.oss-cn-shenzhen.aliyuncs.com/business/39/20221208/2a33419b-a0b4-4f69-b130-cc335504e3bd.png",
    };
  },
  onLoad() {
    if (this.$Route.query.pageId) {
      this.pageId = this.$Route.query.pageId;
    }
    const { isBack, isShare } = this.$Route.query;
    this.isBack = !!isBack;
    this.isShare = !!isShare;
    // this.isPreview = isPreview === true || isPreview === "true";
    this.request();
    this.init();
  },
  watch: {
    sharePanelVisible() {
      this.setPanelTop();
    },
  },
  computed: {
    shareLink() {
      console.log("this.==", this.$route.query);
      const { pageId } = this.$route.query;
      return `${window.location.origin}/#/?pageId=${pageId}&isBack=1&isShare=1`;
    },
    isPreview({ $Route }) {
      const { isPreview } = $Route.query;
      return isPreview === true || isPreview === "true";
    },
  },
  methods: {
    init() {
      this.setInWeChatBrowser();
    },
    setInWeChatBrowser() {
      this.showNavbar = !this.judgeInWeChatBrowser();
    },
    // 判断是否是微信内置浏览器
    judgeInWeChatBrowser() {
      const ua = navigator.userAgent.toLowerCase();
      return ua.match(/MicroMessenger/i) == "micromessenger";
    },
    listenEvent({ eventName, attribute }) {
      if (this[eventName]) {
        this[eventName](attribute);
      }
    },
    swiperClick({ navigateType, url }) {
      if (navigateType === "outside") {
        window.open(url);
      }
    },
    submitForm({ businessId }) {
      businessId = businessId || this.pageData.businessId;
      this.$refs.lpgs.trackFormValidate().then((res) => {
        if (res) return false;
        const params = {
          pageId: this.pageId,
          businessId,
          fromData: this.formatParams(this.$refs.lpgs.getForm()),
        };
        if (this.isPreview)
          return uni.showToast({ icon: "none", title: "预览模式，无法提交" });
        sendData(params)
          .then(() => {
            this.submitSuccess = true;
          })
          .catch((err) => {
            this.submitSuccess = true;
            if (err === "已经删除无法提供服务") {
              this.formIsDeleted = true;
            }
          });
      });
    },
    async getMiniAppQrCode() {
      return await getWxAppQrcode({
        businessId: this.originData.businessId,
        pageId: this.pageId,
      }).then((res) => {
        return res;
      });
    },
    formatParams(data) {
      return data.map((item) => {
        const formatValue = (type, value) => {
          const typeHandle = {
            "yqd-cus-duration-input"(value) {
              const { hour, minute, second } = value;
              return `${hour}时${minute}分${second}秒`;
            },
          };
          return typeHandle[type] ? typeHandle[type](value) : value;
        };
        const value = formatValue(item.type, item.attribute.value);
        return {
          dataId: item.id,
          value: Array.isArray(value) ? value : [value],
        };
      });
    },
    closePage() {
      uni.navigateBack();
    },
    hidePosters() {
      this.postersVisible = false;
    },
    async shareClickHandle() {
      if (!this.pageData?.posterBgImage) {
        uni.showModal({
          title: "提示",
          content: "请完善海报分享资料再分享哦",
          showCancel: false,
          confirmColor: "#ffb72f",
        });
        return;
      }
      const res = await isBindWxapp({ pageId: this.pageId });
      let ShareParams = {
        title: this.pageData.attribute.title,
        desc: this.pageData.attribute.desc,
        type: "link", // link | img
        link: this.shareLink,
        noShare: res.code !== 0,
        imgUrl: this.pageData?.posterBackgroundImage || this.noCover,
      };
      this.sharePanelVisible = true;
      // if (this.AppUtils.getPlatform() === "android") {
      //   this.AppUtils.callFnc("CusFormShare", JSON.stringify(ShareParams));
      // } else {
      //   this.sharePanelVisible = true;
      // }
      console.log("分享的链接-参数", this.shareLink, ShareParams);
      // this.AppUtils.callFnc("CusFormShare", JSON.stringify(ShareParams));
    },
    async showPosters() {
      console.log("分享-showPosters");
      const res = await isBindWxapp({ pageId: this.pageId });
      console.log("showPosters ==", res);
      if (res.code !== 0) {
        return uni.showModal({
          content: "商户还未绑定授权公众号或未绑定小程序",
          showCancel: false,
        });
      }
      this.postersVisible = true;
      this.sharePanelVisible = false;
    },
    shareToFriend() {
      console.log("分享-shareToFriend");
      const ShareParams = {
        shareType: "pic",
        title: this.pageData.attribute.title,
        desc: this.pageData.attribute.desc,
        type: "img", // link | img
        link: this.shareLink,
        imgUrl: this.pageData?.posterBackgroundImage || this.noCover,
      };
      this.AppUtils.callFnc("CusFormShare", JSON.stringify(ShareParams));
      setTimeout(() => {
        this.hidePosters();
      }, 100);
    },
    shareToWechat() {
      console.log("分享-shareToWechat");
      const ShareParams = {
        shareType: "wx",
        title: this.pageData.attribute.title,
        desc: this.pageData.attribute.desc,
        type: "link", // link | img
        link: this.shareLink,
        imgUrl: this.pageData?.posterBackgroundImage || this.noCover,
      };
      this.AppUtils.callFnc("CusFormShare", JSON.stringify(ShareParams));
      setTimeout(() => {
        this.hidePosters();
      }, 100);
    },
    setPanelTop() {
      if (this.sharePanelVisible) {
        this.panelTop = "0vh";
      } else {
        setTimeout(() => {
          this.panelTop = "100vh";
        }, 300);
      }
    },
    async request() {
      this.loadingPage = true;
      await getList({ id: this.pageId })
        .then(async (res) => {
          this.loadingPage = false;
          this.originData = res;
          uni.setStorageSync("businessId", res.businessId);
          uni.setStorageSync("pageId", res.id);
          this.pageData = JSON.parse(res.pageJson);
          this.pageStatus = this.isPreview ? 1 : res.status;
          this.merchantQrCode = await this.getMiniAppQrCode();
        })
        .catch(() => {
          this.loadingPage = false;
        });
      this.loadDone = true;
    },
  },
};
</script>

<style scoped lang="scss">
.content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.xy-center {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.emp-page {
  width: 100vw;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}

.submit-success-view {
  width: 100vw;
  height: 100vh;
  background-color: #f7f7f7;
  display: flex;
  flex-direction: column;
  align-items: center;

  .tips-panel {
    width: 703rpx;
    height: 367rpx;
    background-color: #fff;
    border-radius: 8rpx;
    margin-top: 20rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    box-sizing: border-box;

    .img {
      width: 125rpx;
      height: 125rpx;
      margin-bottom: 26rpx;
    }
  }

  .sild-bar {
    width: 703rpx;
    height: 147rpx;
    display: flex;
    align-items: center;
    padding: 0 42rpx 0 32rpx;
    box-sizing: border-box;
    background-color: #fff;
    margin-top: 20rpx;
    border-radius: 8rpx;

    .qrcode {
      width: 120rpx;
      height: 120rpx;
      background-color: #84e671;
      border-radius: 120rpx;
      overflow: hidden;

      .qrImg {
        width: 100%;
        height: 100%;
        border-radius: 120rpx;
      }
    }
  }
}

.share-panel {
  position: fixed;
  left: 0;
  width: 100vw;
  height: 100vh;
  background-color: #00000031;
  z-index: 11;
  transition: background-color 0.3s;

  .share-content {
    width: 100%;
    height: 395rpx;
    border-radius: 8rpx 8rpx 0 0;
    position: absolute;
    transition: bottom 0.3s;
    left: 0;
    background-color: #fff;
    padding: 34rpx 32rpx 30rpx 32rpx;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    justify-content: space-between;

    .bd {
      display: flex;
      justify-content: space-evenly;

      .item {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;

        .img {
          width: 80rpx;
          height: 80rpx;
          margin-bottom: 24rpx;
        }
      }
    }

    .ft {
      background-color: #ffb72f;
      height: 80rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 30rpx;
    }
  }
}

.posters-content {
  width: 560rpx;
  height: 78vh;
  display: flex;
  flex-direction: column;
  justify-content: space-between;

  .posters-bd {
    position: relative;
    background-color: #fff;
    width: 100%;
    border-radius: 8rpx;
    height: 85%;

    .close-icon {
      position: absolute;
      right: 30rpx;
      top: 30rpx;
      z-index: 9;
    }

    .posters-img {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      object-fit: contain;
    }
  }

  .posters-btn {
    width: 100%;
    height: 80rpx;
    background-color: #ffb72f;
    color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 28rpx;
    border-radius: 30rpx;
  }
}
</style>
